<template>
  <div :id="`uiPrintLog_${info._id}`" :ref="`printLog_${info._id}`" class="printLog w-full" :style="{ height: height + 'px' }">
    <pre :ref="info._id" v-ui-ref="vSetRef">{{ printLogStr }}</pre>
  </div>
</template>
<script>
  import { defineComponent } from 'vue'
  import { UiMixin, ElementsFormMixin, RefsInjectMixin, ConditionMixin } from '@ve/mixin'
  import { domHeight } from '@ve/utils/domHeight'
  import request from '@/utils/request'
  import { GFCD } from '@/utils/utils'
  import isEmpty from 'lodash/isEmpty'
  import isArray from 'lodash/isArray'
  import merge from 'lodash/merge'
  import trim from 'lodash/trim'
  import { processingConstant, replaseRegVariable } from '@ve/utils/utils'

  export default defineComponent({
    name: 'UiPrintLog',
    mixins: [UiMixin, ElementsFormMixin, RefsInjectMixin, ConditionMixin],
    data() {
      return {
        printLog: [],
        printLogStr: '',
        height: 300,
        interval: null,
      }
    },
    computed: {
      printData() {
        return this.$store.getters['diyPrint/getPrintLog']
      },
    },
    watch: {
      printData: {
        handler: function (newval) {
          // 如果有配置接口则不使用websocket数据
          if (this.info.extension.api && this.info.extension.api.value) return
          if (newval && Object.keys(newval).length > 0) {
            this.getPrint(newval)
          }
        },
      },
    },
    created() {
      // 计算高度
      this.getHeight()
      this.$sub(`SplitpaneResized_${this.previewPageId()}`, () => {
        this.getHeight()
      })
    },
    unmounted() {
      this.stopInterval()
    },
    methods: {
      getHeight() {
        setTimeout(() => {
          let _domHeight = domHeight(this)
          console.log('_domHeight 打印机日志', _domHeight)
          if (_domHeight > 0) {
            this.height = _domHeight
          }
        }, 200)
      },
      pushData(val) {
        if (this.printLog.length == this.info.extension.model.value) {
          //超过配置展示条数，就删除第一条
          this.printLog.splice(0, 1)
        }
        this.printLog.push(val)
        this.printLogStr = this.getLogStr(this.printLog)
        this.$nextTick(() => {
          this.$refs[`printLog_${this.info._id}`].scrollTop = this.$refs[`printLog_${this.info._id}`].scrollHeight
        })
      },
      getPrint(val) {
        if (val.fun === 'log' && val.type === 'fun') {
          if (val.LOG) {
            this.pushData(val.LOG)
          }
        }
      },
      getLogStr(list) {
        let str = ''
        list.forEach((r) => {
          str += r
        })
        return str
      },
      requestData(cb) {
        if (!this.info.extension.api || !this.info.extension.api.value) return
        let requestDataObj = {}
        isArray(this.info.extension.requestData.value) &&
          this.info.extension.requestData.value.forEach((item) => {
            let itemVal = item.value
            if (/#{.*?}/g.test(item.value)) {
              itemVal = replaseRegVariable(itemVal, this.info.data.formData)
            }
            requestDataObj[item.key] = processingConstant(this, itemVal)
          })
        let options = {
          api: this.info.extension.api.value,
          method: this.info.extension.method.value,
          getDataKey: this.info.extension.getDataKey.value,
          data: merge(requestDataObj, this.info.data.formData),
        }
        if (!trim(options.api)) return
        this.request(options, cb)
      },
      // 统一请求
      request(options = {}, cb) {
        let getDataKey = this.info.extension.getDataKey.value
        //发起请求
        return request({
          url: GFCD('dams', 'domain') + options.api,
          method: 'post',
          data: {
            data: JSON.stringify(options.data),
            method: options.method,
          },
        }).then((res) => {
          const requestData = isEmpty(getDataKey) ? res.data : res.data[getDataKey]
          this.pushData(requestData)
          // 回调
          cb && cb(res)
        })
      },
      startInterval() {
        if (!this.info.extension.cycleInterval || !this.info.extension.cycleInterval.value) return
        this.interval && clearInterval(this.interval)
        this.interval = setInterval(this.requestData, this.info.extension.cycleInterval.value)
      },
      stopInterval() {
        this.interval && clearInterval(this.interval)
      },
    },
  })
</script>
<style>
  .printLog {
    background-color: #000;
    overflow-y: auto;
    color: #fff;
  }
</style>
